package com.xindong.paking.interceptor;

import com.xindong.paking.exception.CustomerException;
import com.xindong.paking.utils.JwtUtil;
import com.xindong.paking.utils.UserInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果请求为OPTIONS直接放行
        String method = request.getMethod();

        if (method.equals("OPTIONS")) {
            return true;
        }

        // 获取请求头中的token
        String token = request.getHeader("Authorization");

        if (token == null) {
            throw new CustomerException("未登陆");
        }

        // 验证token
        boolean check = JwtUtil.checkSign(token);
        if (!check) {
            throw new CustomerException("登陆过期，请重新登陆");
        }

        Map<String, Object> userInfo = JwtUtil.getInfo(token);

        // 写入ThreadLocal
        UserInfoUtil.setUserInfo(userInfo);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserInfoUtil.removeUser();
    }
}
